package com.fits.auth.api.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.fits.auth.api.dto.SecurityUser;
import com.fits.auth.api.service.login.CommonService;
import com.fits.framework.core.asserts.FitsAssertUtil;
import com.fits.starter.common.security.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private List<CommonService> loginService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        String clientId = StrUtil.isNotBlank(request.getHeader("client_id")) ? request.getHeader("client_id") : request.getParameter("client_id");

        LoginUserDTO dto = null;
        for (CommonService commonService : loginService) {
            if (commonService.getClient().equals(clientId)) {
                dto = commonService.getUser(s);
                break;
            }
        }
        if (ObjectUtil.isEmpty(dto)){
            //此处自定义找不到用户时报错
            //throw new InternalAuthenticationServiceException("用户名/密码无效！");
            throw new UsernameNotFoundException("");
        }
        SecurityUser user = new SecurityUser(dto);
        user.setClientId(clientId);
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        } else if (!user.isCredentialsNonExpired()) {
            throw new LockedException("凭证已过期");
        }
        return user;
    }
}
